package com.sanji.sjmallwidget;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.sanji.sjmallapp.R;
import com.sanji.sjmallmodule.goods.GoodsDetailsActivity;
import com.sanji.sjmallmodule.main.BannerBean;
import com.sanji.sjmallutils.ImageSizeUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 自定义广告显示控件
 * Created by zsf on 16-12-30.
 */

public class BannerPagerView extends ViewPager {

    private static final int ACTION_BANNER_PLAY = 0;
    //轮播时间间隔
    private static final int BANNER_DURATION = 2000;

    private Context mContext;
    //焦点图片的索引
    private int mFocus;
    //控制图片播放
    private Handler mHandler;
    //底部圆点标记view
    private BannerPointView mPointView;
    // true 自动播放 false 手动切换
    private boolean autoSwitch;
    // 播放图片的数量
    private int count;

    private Timer mTimer;
    private BannerViewAdapter mBannerViewAdapter;
    private boolean isRunning;
    private int mCurrentItem;

    private boolean isClick;

    private int bannerWidth;
    private int bannerHeight;


    public BannerPagerView(Context context, AttributeSet attrs) {
        super(context, attrs);

        this.mContext = context;

        initHandler();
        //设置监听
        setListener();

    }

    /**
     * 外部设置数据
     *
     * @param pointView
     * @param list
     * @param isClick    - 图片是否可点击
     * @param bannerType - banner类型，设置图片大小
     */
    public void initBannerData(BannerPointView pointView, List<BannerBean> list, boolean isClick, int bannerType) {

        switch (bannerType) {
            case 0:
                //首页
                bannerWidth = ImageSizeUtil.setImageWidth(mContext, 1);
                bannerHeight = bannerWidth / 2;
                break;
            case 1:
                //详情页
                bannerWidth = bannerHeight = ImageSizeUtil.setImageWidth(mContext, 1);
                break;
        }
//        parentView.setLayoutParams(new LinearLayout.LayoutParams(bannerWidth,bannerHeight));
        ((View) this.getParent()).setLayoutParams(new LinearLayout.LayoutParams(bannerWidth, bannerHeight));
        mPointView = pointView;
        this.isClick = isClick;
        mPointView.setCount(list.size());
        count = mPointView.getCount();
        mBannerViewAdapter = new BannerViewAdapter(list);
        this.setAdapter(mBannerViewAdapter);
    }

    /**
     * 开始播放---用于外部调用方法
     */
    public void startPlay() {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (!isRunning) {
            isRunning = true;
            mTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    mHandler.sendEmptyMessage(ACTION_BANNER_PLAY);
                }
            }, 0, BANNER_DURATION);
        }
    }

    /**
     * 停止播放---外部调用
     */
    public void stopPlay() {
        if (mTimer == null) {
            return;
        }
        isRunning = false;
        mTimer.cancel();
        mTimer = null;
    }


    /**
     * 初始化 handler，接收消息播放动画
     */
    private void initHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case ACTION_BANNER_PLAY:
                        if (!autoSwitch) {
                            autoSwitch = true;
                        } else {
                            // 获取ViewPager中正在播放的索引
                            int pos = BannerPagerView.this.getCurrentItem();
                            pos++;
                            // 设置下一个页面为当前的页面
                            BannerPagerView.this.setCurrentItem(pos);
                        }
                        break;
                }
                super.handleMessage(msg);
            }
        };
    }

    /**
     * 设置监听器
     */
    private void setListener() {
        //设置手指触摸监听器
        setOnTouch();
        //设置ViewPager页面改变的监听器
        setOnPagerChangeListener();
    }

    /**
     * 设置手指触摸监听器
     */
    private void setOnTouch() {
        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE:
                        autoSwitch = false;
                        break;
                }
                return false;
            }
        });
    }

    /**
     * 设置ViewPager页面改变的监听器
     */
    private void setOnPagerChangeListener() {
        this.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                autoSwitch = false;
                mFocus = position % count;
                mPointView.setFocus(mFocus);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    /**
     * banner图片适配器
     */
    private class BannerViewAdapter extends PagerAdapter {

        private List<BannerBean> bannerList = new ArrayList<>();

        public BannerViewAdapter(List<BannerBean> list) {
            this.bannerList = list;
        }

        @Override
        public int getCount() {
            if (count == 0) {
                return 0;
            }
            //无限循环播放
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // 创建一个ImageView对象显示图片
            final ImageView iv = new ImageView(mContext);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
            iv.setLayoutParams(params);
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            mCurrentItem = position % bannerList.size();
            iv.setTag(R.id.banner_tag, mCurrentItem);
            container.addView(iv);
            String url = bannerList.get(mCurrentItem).getBannerUrl();
            //图片下载
            Glide.with(mContext)
                    .load(url)
                    .placeholder(R.mipmap.default_3j_img)
                    .error(R.mipmap.default_3j_img)
                    .into(iv);

            //点击
            if (isClick) {
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int pos = (int) view.getTag(R.id.banner_tag);
                        BannerBean bannerBean = bannerList.get(pos);
                        Intent intent = new Intent(mContext, GoodsDetailsActivity.class);
                        intent.putExtra("goodsCode", bannerBean.getBannerId());
                        intent.putExtra("goodsType", bannerBean.getType());
                        mContext.startActivity(intent);
                    }
                });
            }
            return iv;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
//            super.destroyItem(container, position, object);

        }
    }
}
